<?php

namespace App\Http\Controllers\TK_Api;

use App\Http\Requests\TK\QuestionCollectRequest;
use App\Http\Requests\TK\QuestionReportRequest;
use App\Http\Requests\TK\QuestionResultCheckRequest;
use App\Models\QuestionReport;
use App\Models\Questions;
use App\Models\UserRank;
use Carbon\Carbon;
use DB;
use Illuminate\Http\JsonResponse;

class QuestionsController extends ApiBaseController
{

    /**
     * 获取题目
     * @return JsonResponse|object
     */
    public function list() {
        $ids = explode(',', request('ids'));
        $_list = Questions::whereIn('tiku_questions1.id', $ids)
            ->leftJoin('tiku_question_type', 'tiku_questions1.questionTypeId', '=','tiku_question_type.id')
            ->leftJoin('tiku_knowledge', 'tiku_questions1.thirdKnowledgeId', '=','tiku_knowledge.id')
            ->select([
                'tiku_questions1.id',
                'tiku_questions1.courseId',
                'tiku_questions1.bodyhtml',
                'tiku_questions1.optionCount',
                'tiku_questions1.optionHtmlList',
                'tiku_questions1.optionHtmlList as options',
                'tiku_questions1.answerHtml',
                'tiku_questions1.anylysisHtml',
                'tiku_questions1.rightCount',
                'tiku_questions1.wrongCount',
                'tiku_knowledge.knowledgeName',
                'tiku_question_type.questionTypeName',
            ])
            ->get()->toArray();
        $list = [];
        if (count($_list) > 0) {
            $_userCollectIds = Db::table('tiku_user_collect')->where('userId', $this->user->id)->where('type', 1)->value('ids');
            $userCollectIds = explode(',', $_userCollectIds);

            $_userCuotiIds =  Db::table('tiku_user_cuoti')->where('userId', $this->user->id)->value('ids');
            $userCuotiIds = explode(',', $_userCuotiIds);

            $_userQuestionsIds =  Db::table('tiku_user_questions')->where('userId', $this->user->id)->value('ids');
            $userQuestionsIds = explode(',', $_userQuestionsIds);

            foreach ($_list as $q) {
                $options = explode('|NTK|', $q['options']);
                $optionList = [];
                foreach ($options as $o) {
                    if(empty($o)) continue;
                    $_o = explode('、',$o);
                    if(empty($_o) || count($_o) < 2) continue;
                    $optionList[] = [
                        'key' => $_o[0],
                        'value' => replaceStaticFileUrlInString($_o[1]),
                    ];
                }
                $q['options'] = $optionList;
                $q['bodyhtml'] = replaceStaticFileUrlInString($q['bodyhtml']);
                $q['answerHtml'] = replaceStaticFileUrlInString($q['answerHtml']);
                $q['anylysisHtml'] = replaceStaticFileUrlInString($q['anylysisHtml']);
                $q['rightCount'] = is_null($q['rightCount'])?1:$q['rightCount'];
                $q['wrongCount'] = is_null($q['wrongCount'])?1:$q['wrongCount'];
                $q['rate'] = round($q['rightCount'] / ($q['rightCount'] + $q['wrongCount']), 2) * 100;
                $q['isCollect'] = in_array($q['id'], $userCollectIds);
                $q['isCuoti'] = in_array($q['id'], $userCuotiIds);
                $q['isDone'] = in_array($q['id'], $userQuestionsIds);
                $list[] = $q;
            }
        }

        return $this->restful($list);
    }

    /**
     * 纠错提交
     * @param QuestionReportRequest $request
     * @return JsonResponse|object
     */
    public function report(QuestionReportRequest $request) {
        $params = $request->validated();

        $questionReport = new QuestionReport([
            'userId' => $this->user->id,
            'questionId' => $params['questionId'],
            'type' => $params['type'],
            'content' => $params['content'],
            'createdAt' => Carbon::now(),
        ]);
        $questionReport->save();

        return $this->restful();
    }

    /**
     * 收藏
     * @param QuestionCollectRequest $request
     * @return JsonResponse|object
     */
    public function collect(QuestionCollectRequest $request) {
        $params = $request->validated();

        $ids = explode(',', $params['ids']);

        $collect = Db::table('tiku_user_collect')->where('userId', $this->user->id)->where('type', 1)->first();
        if (!$collect) {
            Db::table('tiku_user_collect')->insert([
                'userId' => $this->user->id,
                'ids' => implode(',', $ids),
                'type' => 1,
            ]);
        } else {
            $collectIds = array_unique(array_merge(explode(',', $collect->ids), $ids));
            if (count($collectIds) > 50) $collectIds = array_slice($collectIds, -50);
            Db::table('tiku_user_collect')->where('userId', $this->user->id)->where('type', 1)
                ->update(['ids' => implode(',', $collectIds)]);
        }

        return $this->restful();
    }

    /**
     * 答题结果报告
     * @param QuestionResultCheckRequest $request
     * @return JsonResponse|object
     */
    public function resultCheck(QuestionResultCheckRequest $request) {
        $params = $request->validated();

        $ids = explode(',', $params['questionIds']);

        Db::transaction(function () use ($params, $ids) {
            // 记录
            $log = Db::table('tiku_user_questions')->where('userId', $this->user->id)->first();
            if (!$log) {
                Db::table('tiku_user_questions')->insert([
                    'userId' => $this->user->id,
                    'ids' => implode(',', $ids)
                ]);
                $idsInLog = $ids;
            }else {
                Db::table('tiku_user_questions')->where('userId', $this->user->id)
                    ->update(['ids' => implode(',', array_unique(array_merge(explode(',', $log->ids), $ids)))]);

                $idsInLog = explode(',', $log->ids);
            }

            // 正确
            if ($params['result'] == 1) {
                $rank = UserRank::where('userId', $this->user->id)->first();
                if (!$rank) {
                    $rank = new UserRank([
                        'userId' => $this->user->id,
                        'count' => count($ids)
                    ]);
                }else {
                    // 去重
                    $newIds = [];
                    foreach ($ids as $id) {
                        if (!in_array($id, $idsInLog)) $newIds[] = $id;
                    }
                    $rank->count += count($newIds);
                }
                $rank->save();

                // 更新正确次数
                Questions::whereIn('id', $ids)->update(['rightCount' => DB::raw('rightCount + 1')]);
            }

            // 错误
            if ($params['result'] == 2) {
                $cuoti = Db::table('tiku_user_cuoti')->where('userId', $this->user->id)->first();
                if (!$cuoti) {
                    Db::table('tiku_user_cuoti')->insert([
                        'userId' => $this->user->id,
                        'ids' => implode(',', $ids)
                    ]);
                }else {
                    $cuotiIds = array_unique(array_merge(explode(',', $cuoti->ids), $ids));
                    if (count($cuotiIds) > 50) $cuotiIds = array_slice($cuotiIds, -50);
                    Db::table('tiku_user_cuoti')->where('userId', $this->user->id)
                        ->update(['ids' => implode(',', $cuotiIds)]);
                }

                // 更新错误次数
                Questions::whereIn('id', $ids)->update(['wrongCount' => DB::raw('wrongCount + 1')]);
            }
        });

        return $this->restful();
    }

    /**
     * 根据ids初始化答题页面
     * @return JsonResponse|object
     */
    public function init() {
        $ids = explode(',', request('ids'));
        $showStatus = request('showStatus', true);

        $_list = Questions::whereIn('id', $ids)
            ->orderBy('id')
            ->select(['id'])
            ->get()->toArray();
        $list['ids'] = [];
        $list['lastId'] = 0;
        $list['lastIndex'] = 0;
        $list['cuotiCount'] = 0;
        $list['correctCount'] = 0;
        $list['collectCount'] = 0;
        if (count($_list) > 0) {
            $_userCollectIds = Db::table('tiku_user_collect')->where('userId', $this->user->id)->where('type', 1)->value('ids');
            $userCollectIds = explode(',', $_userCollectIds);

            $_userCuotiIds =  Db::table('tiku_user_cuoti')->where('userId', $this->user->id)->value('ids');
            $userCuotiIds = explode(',', $_userCuotiIds);

            $_userQuestionsIds =  Db::table('tiku_user_questions')->where('userId', $this->user->id)->value('ids');
            $userQuestionsIds = explode(',', $_userQuestionsIds);

            foreach ($_list as $q) {
                if (in_array($q['id'], $userCollectIds)) {
                    $q['isCollect'] = true;
                    $list['collectCount'] += 1;
                } else {
                    $q['isCollect'] = false;
                }

                if($showStatus) {
                    if (in_array($q['id'], $userCuotiIds)) {
                        $q['isCuoti'] = true;
                        $list['cuotiCount'] += 1;
                    } else {
                        $q['isCuoti'] = false;
                        if (in_array($q['id'], $userQuestionsIds)) $list['correctCount'] += 1;
                    }
                    $q['isDone'] = in_array($q['id'], $userQuestionsIds);
                }else {
                    $q['isCuoti'] = false;
                    $q['isDone'] = false;
                }

                $list['ids'][] = $q;
            }
            $list['lastId'] = $_list[count($userQuestionsIds)-1]['id'] ?? $_list[0]['id'];
            $list['lastIndex'] = count($userQuestionsIds)-1 ?? 0;
        }

        return $this->restful($list);
    }
}
